/*
============================================================================
 Name        : sd_lock.cpp
 Author      : Jian
 Version     :
 Copyright   : GPL
 Description : sd_semp.cpp - source file
============================================================================
*/

/* INCLUDE FILES */
#include "sd_lock.h"
#include <e32cmn.h>
#include <e32base.h>
#include "dd_log.h"

static int count = 0 ;

sd_semp* sd_create_sem(int initVal) 
{
    RSemaphore* sem = NULL ;
    
    count ++ ;
    
    TBuf<10> buf ;
    buf.Zero() ;
    buf.AppendNum(count) ;

    TRAPD(
        err,
        sem = new(ELeave) RSemaphore ;
    CleanupStack::PushL(sem) ;
    User::LeaveIfError(sem->CreateGlobal(buf, initVal));
    CleanupStack::Pop(sem) ;
    ) ;

    if (err != KErrNone)
    {
        // ENGINE_LOG2(_L8("nmsCreateSem create the semaphore = %S error = %d"), &(__ToPtrC8(pName)),err) ;
        sem = NULL ;
    }

    return (void*)sem;
}

int sd_wait_sem(sd_semp* lock) 
{
    __DD_ASSERT_DEFENSE(lock, return -1) ;
    RSemaphore* sem = (RSemaphore*)lock;
    sem->Wait() ;
    return 0;
}

int sd_post_sem(sd_semp* lock) 
{
    __DD_ASSERT_DEFENSE(lock, return -1) ;

    RSemaphore* sem = (RSemaphore*)lock;
    sem->Signal() ;
    return 0;
}

void sd_destroy_sem(sd_semp* lock) 
{
    __DD_ASSERT_DEFENSE(lock, return ) ;

    RSemaphore* sem = (RSemaphore*)lock;
    sem->Close() ;
    delete sem ;
}

sd_rlock* sd_create_rlock() 
{
    RMutex* mutex = new(ELeave) RMutex() ;
    __DD_ASSERT_DEFENSE(mutex, return NULL) ;
    
    int err = KErrNone ;
    if ((err = mutex->CreateLocal()) != KErrNone) {
        dd_log_error("mutex CreateLocal got error: %d", err) ;
        return NULL ;
    }

    return mutex ;
}

int sd_wait_rlock(sd_rlock* lock) 
{
    RMutex* mutex = (RMutex*)lock ;

    __DD_ASSERT_DEFENSE(mutex, return -1) ;

    mutex->Wait() ;
    return 0 ;
}

int sd_post_rlock(sd_rlock* lock) 
{
    RMutex* mutex = (RMutex*)lock ;

    __DD_ASSERT_DEFENSE(mutex, return -1) ;

    mutex->Signal() ;
    return 0 ;
}

void sd_destroy_rlock(sd_rlock* lock) 
{
    RMutex* mutex = (RMutex*)lock ;

    __DD_ASSERT_DEFENSE(mutex, return) ;

    delete mutex ;
}

/* End of File */
